<?php
/*
Plugin Name: Custom Static Components
Description: 一个与主题不相关的UI组件管理插件
Version: 1.0
Author: iori.king
*/

function admin_init() {
    define( 'WPCC_COMPONENT_PLUGIN', __FILE__ );
    define( 'WPCC_COMPONENT_PLUGIN_PATH', dirname( WPCC_COMPONENT_PLUGIN ) );
    define( 'WPCC_COMPONENT_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
    // define( 'WLPFUNMNGPLUGIN_VERSION', '1.0.1' );
    $is_admin = false;
    if(is_admin()) {
        require_once WPCC_COMPONENT_PLUGIN_PATH . '/admin/admin.php';
        require_once WPCC_COMPONENT_PLUGIN_PATH . '/admin/assets.php';
        $is_admin = true;
    }
    return $is_admin;
}

function register_vue_components() {
    // $vue_js = plugin_dir_url(__FILE__) . "assets/global.vue.prod.js";
    // wp_enqueue_script(
    //     "global-vue",
    //     $vue_js,
    //     // "https://unpkg.com/vue@3/dist/vue.global.prod.js",
    //     // "https://cdn.jsdelivr.net/npm/vue@3",
    //     [],
    //     null,
    //     true
    // );
    // wp_enqueue_script(
    //     "tailwindcss",
    //     "https://cdn.tailwindcss.com/3.4.16",
    //     // "https://unpkg.com/vue@3/dist/vue.global.prod.js",
    //     // "https://cdn.jsdelivr.net/npm/vue@3",
    //     [],
    //     null,
    //     true
    // ); 

    if(admin_init()) return;

    $components_dir = plugin_dir_path(__FILE__) . 'components/';
    $components = array_filter(glob($components_dir . '*'), 'is_dir');    
    $components = [];
    // wp_register_script("global-vue-rename", '', [], '', true);
    // wp_add_inline_script("$handle-hydrate", "window.wpcc_vue=window.Vue;window.Vue=undefined;");
    // wp_enqueue_script("$handle-hydrate");

    // wp_enqueue_style(
    //     "wpcc-styles",
    //     "https://cdn.tailwindcss.com"
    // );
    
    function raw_shortcode($atts, $content = null) {
        return $content;
    }
    add_shortcode('raw', 'raw_shortcode');
    
    foreach ($components as $component) {
        $component_name = basename($component);
        add_shortcode(str_replace('-', '_', $component_name), function() use ($component_name) {
            $dom_id = "wp-cc-com-" . uniqid();
            $html_file = plugin_dir_path(__FILE__) . "components/{$component_name}/{$component_name}.html";
            $script_file = plugin_dir_path(__FILE__) . "components/{$component_name}/{$component_name}.bundle.js";
            $script_url = plugin_dir_url(__FILE__) . "components/{$component_name}/{$component_name}.bundle.js";
            $style_file = plugin_dir_url(__FILE__) . "components/{$component_name}/{$component_name}.css";
            $html = file_get_contents($html_file);            
            $jsstr = file_get_contents($script_file);
            // 启用内部错误处理
            libxml_use_internal_errors(true);

            // 创建 DOMDocument 实例
            $dom = new DOMDocument();
            // 加载 HTML
            $dom->loadHTML($html);
            $xpath = new DOMXPath($dom);
            // 清除错误信息
            libxml_clear_errors();

            $root_dom = $xpath->query('/html/body/*[1]')->item(0);
            // 检查并输出结果
            if ($root_dom) {
                $root_dom -> setAttribute($dom_id, '');
            }
            $nhtml = $dom -> saveHTML();
            
            if (file_exists($html_file)) {
                // 加载 HTML 片段
                $html = $nhtml;
                $handle = "vue-component-{$component_name}";
                if (!wp_script_is($handle, 'registered')) {
                    // $jsstr = preg_replace('/^var\s+[a-zA-Z_$][a-zA-Z0-9_$]*=\s*/', "window.wpcc_components=window.wpcc_components||{};window.wpcc_components['$component_name']=", $jsstr);
                    // $jscontent = <<<EOT
                    // ;(function($){var component=$jsstr})(window.Jquery? Jquery: null)
                    // EOT;
                    wp_register_script("vue-component-{$component_name}", $script_url, [], '', true);
                    // wp_add_inline_script($handle, $jscontent);
                    wp_enqueue_script("vue-component-{$component_name}");
                }
                
                wp_register_script("$handle-hydrate", '', [], '', true);
                wp_add_inline_script("$handle-hydrate", "(function(){document.addEventListener('DOMContentLoaded', function(){const mountPoint=document.querySelector('[$dom_id]');if(!mountPoint) return;const app = \$wpcc_vue.createApp(window.wpcc_components['$component_name']);const componentInstance = app.mount(mountPoint);const componentRoot = componentInstance.\$el;mountPoint.parentNode.replaceChild(componentRoot, mountPoint);})})();");
                wp_enqueue_script("$handle-hydrate");

                wp_enqueue_style(
                    "$handle",
                    $style_file
                );

                remove_filter('the_content', 'wpautop');
                $output = $html;
                add_filter('the_content', 'wpautop');
                return $output;
            }
            return 'Component not found';
        });
    }
}

final class Wpcsc_Components_Center_Plugin{    
    /**
     * Holds various class instances
     *
     * @var array
     */
    private $container = array();
    public function __construct() {
        add_action('init', 'register_vue_components');
    }

    /**
     * Initializes the Wp_Functions_Manager_Plugin() class
     *
     * Checks for an existing Wp_Functions_Manager_Plugin() instance
     * and if it doesn't find one, creates it.
     */
    public static function init() {
        static $instance = false;

        if ( ! $instance ) {
            $instance = new Wp_Functions_Manager_Plugin();
        }

        return $instance;
    }
}

new Wpcsc_Components_Center_Plugin();
?>
